package com.ygj.inspection.service.impl;

import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import com.base.common.persistent.model.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.base.common.ConfigConstants;
import com.base.common.entity.InspectionTicket;
import com.base.common.enums.InspectionTicketCategories;
import com.base.common.json.JsonUtil;
import com.base.common.persistent.dao.EmployeeCompoundsMapper;
import com.base.common.persistent.dao.InspectionCategoriesMapper;
import com.base.common.persistent.dao.InspectionPointMapper;
import com.base.common.persistent.dao.InspectionProjectMapper;
import com.base.common.persistent.dao.InspectionTicketDetailsMapper;
import com.base.common.persistent.dao.InspectionTicketMapper;
import com.ygj.inspection.service.InspectionService;

@Service("inspectionService")
public class InspectionServiceImpl implements InspectionService {

	@Resource
	private InspectionProjectMapper inspectionProjectMapper;

	@Resource
	private InspectionTicketMapper inspectionTicketMapper;
	
	@Resource
	private InspectionPointMapper inspectionPointMapper;

	@Resource
	private InspectionCategoriesMapper inspectionCategoriesMapper;

	@Resource
	private InspectionTicketDetailsMapper inspectionTicketDetailsMapper;

	@Resource
	private EmployeeCompoundsMapper employeeCompoundsMapper;

	@Override
	public List<InspectionProject> getInspectionProject(
			int flag, int inspectionCategories, String inspectionPointCode) {
		return inspectionProjectMapper
				.getInspectionProjectByCompoundsIdAndInspectionCategoriesAndInspectionPointCode(
						flag, inspectionCategories, inspectionPointCode);
	}

	@Transactional
	@Override
	// 经纬度，员工小区中间id
	public int subInspectionTicket(int employeeId,
			List<String> inspectionProjectsStatusList, String coordinates,
			int compoundsId) {
		int result = 0;
		// 添加巡查工单
		String code = getCode(InspectionTicketCategories.INSPECTION.getName()); // 生成工单code
		com.base.common.persistent.model.InspectionTicket inspectionTicket = new com.base.common.persistent.model.InspectionTicket();
		inspectionTicket.setInspectionTime(new Date());
		inspectionTicket.setEmployeeCompoundsId(employeeCompoundsMapper
				.queryEmployeeCompoundsIdByEmployeeIdAndCompoundsId(employeeId,
						compoundsId));
		inspectionTicket.setCode(code);
		inspectionTicket.setCoordinates(coordinates);
		result = inspectionTicketMapper.addInspectionTicket(inspectionTicket);

		// 添加巡查工单详细
		InspectionTicketDetails inspectionTicketDetails = new InspectionTicketDetails();
		System.out.println(code);
		inspectionTicketDetails.setInspectionTicket(inspectionTicketMapper
				.queryInspectionTicketByCode(code));
		for (String inspectionProjectsStatus : inspectionProjectsStatusList) {
			inspectionTicketDetails.setStatus(JsonUtil.string2Obejct(
					inspectionProjectsStatus, InspectionTicket.class)
					.getStatus());
			InspectionPointsProject inspectionPointsProject = new InspectionPointsProject();
			inspectionPointsProject.setId(JsonUtil.string2Obejct(
					inspectionProjectsStatus, InspectionTicket.class)
					.getInspectionPointsProjectId());
			inspectionTicketDetails
					.setInspectionPointsProject(inspectionPointsProject);
			inspectionTicketDetailsMapper
					.addInspectionTicketDetails(inspectionTicketDetails);
		}

		return result;
	}

	@Override
	public List<InspectionCategories> getAllInspectionCategories() {
		return inspectionCategoriesMapper.getAllInspectionCategories();
	}

	/**
	 * 生成巡查工单工单号
	 * 
	 * @return
	 */
	@Transactional
	private String getCode(String prefixCode) {
		String lastedCode = inspectionTicketMapper.queryLastCode();
		DecimalFormat df = new DecimalFormat(ConfigConstants.TICKET_CODE_NUMS);
		String code = null;
		if (lastedCode != null && lastedCode.trim() != "") {
			code = df
					.format(Integer.parseInt(lastedCode.substring(1).trim()) + 1);
		} else {
			code = df.format(1);
		}
		code = prefixCode + code;
		return code;
	}

	@Override
	public Object getInspectionPointNameByCode(String code, int flag) {
		return inspectionPointMapper.getInspectionPointNameByCode(code.trim(), flag);
	}

	/* (non-Javadoc)
	 * @see com.ygj.inspection.service.InspectionService#getInspectionTicketCountsGroupByPointByDate(int, java.lang.String, java.lang.String)
	 */
	/*@Override
	public Object getInspectionTicketCountsGroupByPointByDate(int compoundsId, String startTime, String endTime) {
		List<Map> maps = inspectionTicketMapper.getInspectionTicketCountsGroupByPointByDate(compoundsId, startTime, endTime);
		List<Map> results = new ArrayList<Map>();
		for(Map aa : maps){
			
			int index = 0;
			
			int[] is = new int[24];
			
			int counts = Integer.valueOf(String.valueOf(aa.get("counts")).trim());
			int id = Integer.valueOf(String.valueOf(aa.get("id")).trim());
			Object name = aa.get("name");
            int orderDay = 0;
            if (aa.get("orderDay") != null){
                orderDay = Integer.valueOf(String.valueOf(aa.get("orderDay")).trim());
            }

			for(int i = 0; i < results.size(); i++){
				Map result = results.get(i);
				int bbId = Integer.valueOf(String.valueOf(result.get("id")).trim());
				if(id == bbId){
                    int[] js = (int[]) result.get("hourTicketCounts");
                    if (aa.get("orderDay") != null){
                        js[orderDay] = counts;
                    } else {
                        js[orderDay] = 0;
                    }
                    result.put("hourTicketCounts", js);
					results.set(i, result);
					break;
				}
			}
			
			if(index == 0){
				Map map = new HashMap();
				map.put("id", id);
				map.put("name", name);

                if (aa.get("orderDay") != null){
				    is[orderDay] = counts;
                } else {
                    is[orderDay] = 0;
                }
				map.put("hourTicketCounts", is);
				results.add(map);
			}
		}
        *//*List<Map> results = new ArrayList<>();

        List<PointHour> pointHours = inspectionTicketMapper.selectPointIdHour(compoundsId, startTime, endTime);
        for (PointHour pointHour : pointHours) {
            Map<String, Object> objectMap = new HashMap<>();

            // 获取巡查点名称
            int pointId = pointHour.getPointId();
            objectMap.put("id", pointId);
            InspectionPoints inspectionPoints = inspectionPointMapper.getInspectionPointById(pointId);
            String pointName = inspectionPoints.getName();
            objectMap.put("name", pointName);
//            System.out.println(pointName);

            // 初始化24小时巡查状态
            int[] inspectionStatus = new int[24];
//            for(int status : inspectionStatus) status = 0;

            List<Hour> hourList = pointHour.getHourList();
            for (Hour hour : hourList) {
//                System.out.println(hour.getHour());
                int h = hour.getHour();
                int count = inspectionTicketMapper.getIsExistInspectionByCondition(startTime, endTime, pointId, hour.getHour());
                if (count > 0) {
                    inspectionStatus[h] = -1;
                } else {
                    inspectionStatus[h] = 1;
                }
//                System.out.println(isExistInspectionByCondition);
            }
            objectMap.put("hourTicketCounts", inspectionStatus);
            results.add(objectMap);
        }*//*
        return results;
	}*/

	public Object getInspectionTicketCountsGroupByPointByDate(int compoundsId, String startTime, String endTime) {
        List<Map> results = new ArrayList<Map>();
        List<InspectionPoints> inspectionPoints = inspectionPointMapper.getInspectionPointByCompoundsId(compoundsId);
        if (inspectionPoints.size() > 0) {

            List<com.base.common.persistent.model.InspectionTicket> inspectionTickets = inspectionTicketMapper.selectByPointIdsAndDateTime(inspectionPoints.stream().map(InspectionPoints::getId).collect(Collectors.toList()), startTime, endTime);
//			System.out.println(inspectionTickets.size());
//			inspectionTickets.forEach((item) -> System.out.println(item.getId() + "\t" + item.getInspectionTime()  + "\t" + item.getInspectionPoints().getId()));
			inspectionPoints.stream().forEach((inspectionPoint) -> {
                Map<String, Object> inspectionPointInfo = new LinkedHashMap<>();
				inspectionPointInfo.put("id", inspectionPoint.getId());
				inspectionPointInfo.put("name", inspectionPoint.getName());
                int[] inspectionStatus = new int[]{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
                List<com.base.common.persistent.model.InspectionTicket> inspectionTicketList = inspectionTickets.stream().filter(item -> item.getInspectionPoints().getId() == inspectionPoint.getId()).collect(Collectors.toList());
                if (inspectionTicketList.size() > 0) {
                    inspectionTicketList.forEach((item) -> {

//                        System.out.println(item.getId() + "\t" + item.getInspectionTime()  + "\t" + item.getInspectionPoints().getId());
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(item.getInspectionTime());
                        int hour = calendar.get(Calendar.HOUR_OF_DAY);
//                        System.out.println("时间\t" + item.getInspectionTime()  + "\t小时\t" + hour);
                        inspectionStatus[hour] = 1;
                    });
                }
                inspectionPointInfo.put("hourTicketCounts", inspectionStatus);
                results.add(inspectionPointInfo);
            });
        }
        return results;
	}

	/* (non-Javadoc)
	 * @see com.ygj.inspection.service.InspectionService#getInspectionTicketListGroupByPointByDateTime(int, java.lang.String, java.lang.String, int, int)
	 */
	@Override
	public Object getInspectionTicketListGroupByPointByDateTime(int compoundsId, String startTime, String endTime,
			int hour, int inspectionPointID) {
		
		return inspectionTicketMapper.getInspectionTicketListGroupByPointByDateTime(compoundsId, startTime, endTime, hour, inspectionPointID);
	}

	@Override
	public List<InspectionCategories> getInspectionCategoriesByPoint(int inspectionPointId) {
		return inspectionCategoriesMapper.getInspectionCategoriesByPointId(inspectionPointId);
	}

}
